using System;
using UnityEngine;

public class DemoOHETsObject
{
    private string logString = "";
    private OpenHarmonyJSClass m_ohJSClass = null;
    private OpenHarmonyJSObject m_ohJSObject = null;

    public string Test()
    {
        if (m_ohJSClass == null)
        {
            m_ohJSObject = new OpenHarmonyJSObject("ObjectDefineInETS");
        }

        logString = string.Empty;
        TestObjectMethods();

        return logString;
    }

    private void TestObjectMethods()
    {
        m_ohJSObject.Call("FuncVoid", "Tuanjie & OpenHarmony", 9527);
        LogInvoke<int>("MeaningOfLife");
    }

    private void LogInvoke<ReturnType>(string methodName, params object[] args)
    {
        var result = m_ohJSObject.Call<ReturnType>(methodName, args);
        Log($"{methodName}<{typeof(ReturnType).Name}>({ArgsToString(args)})={ReturnToString(result)}");
    }

    private ReturnType LogGet<ReturnType>(string fieldName)
    {
        var result = m_ohJSObject.Get<ReturnType>(fieldName);
        Log($"GetStatic<{typeof(ReturnType).Name}>(\"{fieldName}\")={ReturnToString(result)}");
        return result;
    }
    
    private void LogSet<FieldType>(string fieldName, FieldType val)
    {
        var result = m_ohJSObject.Set<FieldType>(fieldName, val);
        Log($"Set<{typeof(FieldType).Name}>(\"{fieldName}\", {ArgsToString(val)})={ReturnToString(result)}");
    }

    private string ArgsToString(params object[] args)
    {
        if (args == null || args.Length == 0)
            return "";
        
        var ret = $"{args[0]}";
        for (int i = 1; i < args.Length; i++)
        {
            ret += $", {args[i]}";
        }

        return ret;
    }

    private string ReturnToString(object obj)
    {
        if (obj.GetType().IsArray)
        {
            return ArrayToString(obj as Array);
        }

        return obj.ToString();
    }

    private string ArrayToString(Array array)
    {
        string log = array.Length + ":[";
        for (int i = 0; i < array.Length; i++)
        {
            if (i == 0)
                log += array.GetValue(i);
            else
                log += ", " + array.GetValue(i);
        }

        log += "]";
        return log;
    }

    private void Log(string log)
    {
        Debug.Log(log);
        logString += log.Replace('\0', ' ') + "\n";
    }
}
